package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.AirCarbinParser.CarbinItem;
import com.myapp.ruyixing.http.AirCarbinParser.Carbins;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.Airline.AirlineSearchItem;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.SafeUtils;

public class AirTicketSubmitActivity extends BaseActivity implements
		OnClickListener {

	private Spinner mClassView;
	private View mLoadingView;

	private String passengerName;
	private String passengerCode;
	private String passengerType;
	private String passengerBirth;

	private AirlineSearchItem mData;

	private Map<String, String> ticketNameToPrice = new HashMap<String, String>();
	private Map<String, String> ticketNameToPrice2 = new HashMap<String, String>();

	private RYHttpResponseHandler mHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			Carbins t = (Carbins) o;

			if (t != null && t.list != null) {
				ArrayList<String> testarray = new ArrayList<String>();
				for (CarbinItem item : t.list) {
					testarray.add(item.cabintypename_go);
					ticketNameToPrice.put(item.cabintypename_go, item.price_go);
					int discount = SafeUtils.safeString2int(item.discount_go);
					int price = SafeUtils.safeString2int(item.price_go);
					int price2 = discount != 0 ? price * 10 / discount : 0;
					ticketNameToPrice2.put(item.cabintypename_go, "" + price2);
				}
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						AirTicketSubmitActivity.this,
						R.layout.cell_air_ticket_class2, testarray);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				mClassView.setAdapter(adapter);
				mClassView
						.setOnItemSelectedListener(new OnItemSelectedListener() {
							@Override
							public void onItemSelected(
									android.widget.AdapterView<?> parent,
									View view, int position, long id) {
								String name = (String) mClassView
										.getSelectedItem();
								String price = ticketNameToPrice.get(name);
								((TextView) findViewById(R.id.price))
										.setText(price);
								((TextView) findViewById(R.id.total_price))
										.setText("订单总额 " + price);
								((TextView) findViewById(R.id.price_normal))
										.setText(ticketNameToPrice2.get(name));
							};

							@Override
							public void onNothingSelected(
									android.widget.AdapterView<?> parent) {

							};
						});

			} else if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();

				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						finish();
					}
				}, 1000);
			}

			hideLoading();
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();

				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						finish();
					}
				}, 1000);
			}
			hideLoading();
		}
	};

	private RYHttpResponseHandler mCommitHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			Toast.makeText(AirTicketSubmitActivity.this, "预定成功",
					Toast.LENGTH_LONG).show();
			setResult(RESULT_OK);
			finish();
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "预定失败",
						Toast.LENGTH_SHORT).show();
			}

			hideLoading();
		}
	};

	private void showLoading() {
		mLoadingView.setVisibility(View.VISIBLE);
	}

	private void hideLoading() {
		mLoadingView.setVisibility(View.GONE);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_air_ticket_order_submit);

		mData = (AirlineSearchItem) getIntent().getSerializableExtra("data");

		initView();

		showLoading();
		RYHttpClient.getAirCarbins(this, mHandler, mData.fromCity,
				mData.toCity, mData.date, mData.getAircode(), 1);
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);

		if (arg1 == RESULT_OK && arg2 != null) {
			passengerName = arg2.getStringExtra("name");
			passengerCode = arg2.getStringExtra("code");
			passengerType = arg2.getStringExtra("type");
			passengerBirth = arg2.getStringExtra("birthday");

			((TextView) findViewById(R.id.passenger_name))
					.setText(passengerName);
			findViewById(R.id.add_passenger).setVisibility(View.GONE);
		}
	}

	private void initView() {

		mClassView = (Spinner) findViewById(R.id.choose_class);
		mLoadingView = findViewById(R.id.my_loading);

		((TextView) findViewById(R.id.from)).setText(mData.date
				+ mData.fromName + "-" + mData.toName);
		((TextView) findViewById(R.id.airplane)).setText(mData.planeinfo_go);
		((TextView) findViewById(R.id.start)).setText(mData.getTimeStart());
		((TextView) findViewById(R.id.from)).setText(mData.getAirportFrom());
		((TextView) findViewById(R.id.arrive_time)).setText(mData
				.getTimeArrive());
		((TextView) findViewById(R.id.arrive))
				.setText(mData.getAirportArrive());

		TextView mPriceNormalView = (TextView) findViewById(R.id.price_normal);
		mPriceNormalView.getPaint().setFlags(
				Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

		findViewById(R.id.add_passenger).setOnClickListener(this);
		findViewById(R.id.submit).setOnClickListener(this);

		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add_passenger:
			startActivityForResult(
					new Intent(this, AddPassengerActivity.class), 0);
			break;
		case R.id.submit:
			showLoading();
			RYHttpClient
					.commitAirlineOrder(this, mCommitHandler, mData.fromCity,
							mData.toCity, mData.getAirCompany(), mData
									.getAircode(), mData.getAirType(), mData
									.getAirportFrom(),
							mData.getAirportArrive(),
							mData.date + " " + mData.getTimeStart(),
							(String) mClassView.getSelectedItem(),
							((TextView) findViewById(R.id.price)).getText()
									.toString(), mData.airportfee,
							mData.fuelfee,
							((TextView) findViewById(R.id.phone)).getText()
									.toString(), passengerName, passengerCode,
							passengerType, passengerBirth);
			break;

		default:
			break;
		}
	}
}
